#!/usr/bin/env python
#encoding:utf8


'''the usage just like `xprocessing.py`
'''

import time
import threading
from Queue import Queue

# from threading import Lock, RLock

Process = threading.Thread

def gen_queue(**kargs):
    return Queue(**kargs)


# generate one processing to generate queue
def as_process(name="producer", is_daemon=True, is_join=False):
    def wrapper(func):
        def _wrapper(*args, **kargs):
            p = Process(target=func, name=name, args=args, kwargs=kargs)
            if is_daemon: p.setDaemon(True)
            p.start()
            if is_join: p.join()
            return p
        return _wrapper
    return wrapper


# generate processes
def as_processes(name='processing', tasks_num=4, is_daemon=True, is_join=False):
    def wrapper(func):
        def _wrapper(*args, **kargs):
            processes = []
            for i in xrange(tasks_num):
                p_name = "%s(%s)"%(name, i+1)
                processes.append(Process(target=func, name=p_name, args=args, kwargs=kargs))
            if is_daemon:
                for p in processes:
                    p.setDaemon(True)
            for p in processes:
                p.start()
            if is_join:
                for p in processes:
                    p.join()
            return processes
        return _wrapper
    return wrapper

# generate process pool
def as_process_pool(name="consumer", tasks_num=4):
    def wrapper(func):
        def _wrapper(*args, **kargs):
            p = Pool(processes=tasks_num) 
            #while 1:
            p.apply_async(func, args=args, kwds=kargs)
            return p
        return _wrapper
    return wrapper


